package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.service.impl
 */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 查询所有的班级列表
     *
     * @return
     */
    @Override
    public List<Clazz> list() {
        return clazzMapper.selectAll();
    }

    /**
     * 新增班级
     *
     * @param clazz
     */
    @Override
    public void add(Clazz clazz) {
        // 补全属性值
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(clazz.getCreateTime());
        clazzMapper.insert(clazz);
    }

    /**
     * 分页查询班级
     *
     * @param clazzQueryParam
     * @return
     */
    @Override
    public PageResult<Clazz> pageQuery(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        Page<Clazz> pageInfo = clazzMapper.pageQuery(clazzQueryParam);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }

    /**
     * 通过id删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        Integer exists = studentMapper.existsWithClazzId(id);
        if(exists > 0){
            throw new RuntimeException("班级下存在学生，不能删除!");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.selectById(id);
    }

    @Override
    public void updateById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }
}
